package cn.glutnn.interceptors;

import cn.glutnn.utils.JwtUtil;
import cn.glutnn.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * Author:   msh
 * Date:     2024/10/25 上午10:56
 * Description:
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 验证token
        String token = request.getHeader("token");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            String redisToken = redisTemplate.opsForValue().get("rxtToken");

            if (redisToken == null) {
                response.setStatus(401);
                response.setHeader("Content-Type", "application/json;charset=UTF-8");
                response.getWriter().write("请先登录");
                // 拦截
                return false;
            }

            ThreadLocalUtil.set(claims);
            // 放行
            return true;
        } catch (Exception e) {

            response.setStatus(401);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write("请先登录");
            // 拦截
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除线程变量
        ThreadLocalUtil.remove();
    }
}
